package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: Sabrina
 * @Date:2025/06/18/9:36
 * @Description:
 */
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单支付超时的问题
     */
    @Scheduled(cron = "* */5 * * * ?")
    public void theProcessingOrderTimedOut() {
//        SELECT * FROM ORDERS WHERE STATUS = 1 AND ORDER_TIME < NOW() -15FENZHONG
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//当前系统时间,15分钟前的时间
        List<Orders> orders = orderMapper.getOrdersByOrderTime(time);
        if (orders != null && orders.size() > 0) {
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时,自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    @Scheduled(cron = "* */5 * * * ?")
    public void ordersAreBeingDelivered() {
//        SELECT * FROM ORDERS WHERE STATUS = 1 AND ORDER_TIME < NOW() -15FENZHONG
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//当前系统时间,60分钟前的时间
        List<Orders> orders = orderMapper.getOrdersByOrderTime2(time);
        if (orders != null && orders.size() > 0) {
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
//        System.out.println("当前时间: " + LocalDateTime.now());
//        System.out.println("目标时间: " + time);
//        System.out.println("查询结果数量: " + orders.size());
    }
}
